package servlet;

import com.jspsmart.upload.File;
import com.jspsmart.upload.SmartUpload;
import com.jspsmart.upload.SmartUploadException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.JspFactory;
import javax.servlet.jsp.PageContext;
import java.io.IOException;

@WebServlet(urlPatterns = "/upload")
public class UploadServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            //1.创建上传文件的对象
            SmartUpload smartUpload = new SmartUpload();

            //2.初始化
            //第一个参数是servlet对象，第二个第三个是req和resp,第四个是jsp的错误页面null是不指定，
            //第五个是是否使用session，第六个是缓冲区大小，第七个是是否自动填入缓冲区的内容
            PageContext pageContext = JspFactory.getDefaultFactory().getPageContext(this, req, resp, null, false, 1024, true);
            smartUpload.initialize(pageContext);

            //3.设置编码
            smartUpload.setCharset("utf-8");

            //4.上传
            smartUpload.upload();

            //5.获取文件信息
            File file = smartUpload.getFiles().getFile(0);
            String fileName = file.getFileName();
            String contentType = file.getContentType();
            System.out.println(fileName);
            //6.指定上传路径
            String uploadPath = "/uploadfiles/"+fileName;

            //7.保存到指定位置
            file.saveAs(uploadPath, File.SAVEAS_VIRTUAL);

            //8.跳转成功页面
            req.setAttribute("filename",fileName);

            req.getRequestDispatcher("success.jsp").forward(req,resp);
        } catch (SmartUploadException e) {
            e.printStackTrace();
        }
    }
}
